using System;
using RayDen.Library.Core.Primitives;

namespace RayDen.Library.Data.Import.Loader3DS {


    internal class SceneEntity {
        public string ObjectName;
    }

    internal class ModelEntity : SceneEntity {
        // TODO: OO this
        // fields should be private
        // constructor with verts and faces
        // normalize in ctor
        public struct Triangle {
            public UInt32 vertex1, vertex2, vertex3;
            public Triangle(uint v0, uint v1, uint v2) {
                vertex1 = v0;
                vertex2 = v1;
                vertex3 = v2;
            }
        }

        public MaterialEntity material = new MaterialEntity();

        // The stored vertices 
        public Vector[] vertices;

        public int VertexOffset;

        // The calculated normals
        public Vector[] normals;

        // The indices of the triangles which point to vertices
        public Triangle[] indices;

        // The coordinates which map the texture onto the entity
        public UV[] texcoords;


        //bool normalized = false;

        public void CalculateNormals() {
            if (indices == null) return;

            normals = new Vector[vertices.Length];

            var temps = new Vector[indices.Length];

            for (int ii = 0; ii < indices.Length; ii++) {
                var tr = indices[ii];

                var v1 = vertices[tr.vertex1] - vertices[tr.vertex2];
                var v2 = vertices[tr.vertex2] - vertices[tr.vertex3];

                temps[ii] = v1 ^ v2;
            }

            for (int ii = 0; ii < vertices.Length; ii++) {
                var v = new Vector();
                int shared = 0;

                for (int jj = 0; jj < indices.Length; jj++) {
                    Triangle tr = indices[jj];
                    if (tr.vertex1 == ii || tr.vertex2 == ii || tr.vertex3 == ii) {
                        v += temps[jj];
                        shared++;
                    }
                }

                normals[ii] = (v / shared).Normalize();
            }
            //normalized = true;
        }

    }
}